from datetime import timedelta, datetime, timezone

import jwt
from passlib.context import CryptContext

from app.config.env import env

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


class CryptUtils:
  @staticmethod
  def get_password_hash(password: str):
    return pwd_context.hash(password)

  @staticmethod
  def verify_password(plain_password: str, hashed_password: str):
    return pwd_context.verify(plain_password, hashed_password)

  @staticmethod
  def create_access_token(username: str, expires_delta: timedelta | None = None):
    data: dict = {"sub": username}
    if expires_delta:
      expire = datetime.now(timezone.utc) + expires_delta
    else:
      expire = datetime.now(timezone.utc) + timedelta(minutes=env.jwt_access_token_expire_minutes)
    data.update({'exp': expire})
    return jwt.encode(data, env.jwt_secret_key, env.jwt_algorithm)

  @staticmethod
  def get_username_from_token(token: str):
    data = jwt.decode(token, env.jwt_secret_key, algorithms=[env.jwt_algorithm])
    username = data.get("sub")
    return username
